<?php
#
# author: Cody Sorgenfrey
# ©2013 South Hill Calvary Chapel
#
include("../common.php");

$title = "Church Membership Questionnaire Manager";
print_html_head($title, NULL, NULL);
print_java_head(NULL);
?>
	<style>
		#loginBox{
			width: 200px;
			height: 140px;
			text-align: center;
			padding-top: 30px;
			margin-right: auto;
			margin-left: auto;
			border-radius: 5px;
			box-shadow: 1px 1px 5px black;
		}
		#loginError{
			color: red;
		}
		#noPass{
			margin-top: 10px;
			font-size: 80%;
			text-align: center;
		}
		#picker{
			width: 24.5%;
		}
		#selectedMessage{
			width: 71.5%;
			padding-left: 3%;
			overflow: hidden;
		}
		#picker,
		#selectedMessage{
			display: inline-block;
			vertical-align: top;
		}
		#searchBox{
			width: 56%;
			border: none;
			outline: none;
			margin: 5px 0px 5px 0px
		}
		#SMHeader{
			width: 100%;
			margin-bottom: 30px;
		}
		#SMHeader>h3{
			font-size: 16pt;
			margin-bottom: 0px;
		}
		#SMHeader>p{
			font-size: 10.5pt;
			margin: 0px;
		}
		div.actions{
			float: right;
			text-align: right;
		}
		.actions>button{
			font-size: 10pt;
			font-family: Gnuolane;
			background-color: #eeeeee;
			border: 1px solid black;
			border-radius: 7px 7px 7px 7px;
		}
		p.notes{
			font-size: 10pt;
		}
		textarea{
			width: 95%;
			max-width: 680px;
			height: 200px;
		}
		#SMContent{
			max-width: 700px;
			word-break: break-word;
		}
		#SMContent>b{
			font-size: 10.5pt;
		}
		button{
			outline: none;
			margin-bottom: 5px;
		}
		#buttonHolder{
			width: 100%;
			text-align: center;
			margin: 10px 0px;
		}
		div.filter{
			display: inline-block;
			width: 29%;
			height: 18px;
			font-size: 9pt;
			font-family: Gnuolane;
			background-color: #eeeeee;
			border: 1px solid black;
			padding: 5px;
			cursor: pointer;
			margin: -1%;
			text-overflow: ellipsis;
			overflow: hidden;
		}
		div.filter:last-of-type{
			border-radius: 0px 10px 10px 0px;
		}
		div.filter:first-of-type{
			border-radius: 10px 0px 0px 10px;
		}
		div.filter.selected{
			box-shadow: inset 1px 1px 5px black;
			background-color: #dbdbdb;
		}
		#mailbox{
			width: 94%;
			min-height: 200px;
			max-height: 600px;
			background-color: #eeeeee;
			box-shadow: inset 1px 1px 7px black;
			border-radius: 5px;
			padding: 3%;
		}
		div.message{
			width: 96%;
			padding: 2%;
			margin-bottom: 2px;
			border-radius: 5px;
			box-shadow: 1px 1px 3px black;
			background-color: white;
			cursor: pointer;
		}
		div.message.selected{
			background-color: #c4d7e5;
		}
		div.message.hidden,
		div.message.dontShow{
			display: none;
		}
		div#order{
			width: 100%;
			text-align: center;
			margin-top: 5px;
		}
		table{
			table-layout: fixed;
		}
		td{
			padding: .3%;
			text-overflow: ellipsis;
			overflow: hidden;
			white-space: nowrap;
		}
		td:last-child{
			text-align: right;
		}
		td:first-child{
			font-family: Gnuolane;
			font-size: 12pt;
		}
	</style>
	<script type="text/javascript">
		$(document).ready(function(){
			loadData();
		});
		function reorderTable(i){
			switch (i) {
				case 0: //sort by date Desc
					$("div.message").sort(sortByDateDesc).appendTo("#mailbox");
					break;
				case 1: //sort by date asc
					$("div.message").sort(sortByDateAsc).appendTo("#mailbox");
					break;
				case 2: //sort by name Desc
					$("div.message").sort(sortByNameDesc).appendTo("#mailbox");
					break;
				case 3: //sort by name asc
					$("div.message").sort(sortByNameAsc).appendTo("#mailbox");
					break;
			}
		}
		function sortByDateAsc(a, b){
			var myA = $(a).data("questionnaire").mysqlDate;
			var myB = $(b).data("questionnaire").mysqlDate; 
			if (myA > myB){
				return 1;
			} else if (myA < myB){
				return -1;
			} else {
				return 0;
			}
		}
		function sortByDateDesc(a, b){
			var myA = $(a).data("questionnaire").mysqlDate;
			var myB = $(b).data("questionnaire").mysqlDate; 
			if (myB > myA){
				return 1;
			} else if (myB < myA){
				return -1;
			} else {
				return 0;
			}
		}
		function sortByNameAsc(a, b){
			var myA = $(a).data("questionnaire").name.toUpperCase().split(" ")[1];
			var myB = $(b).data("questionnaire").name.toUpperCase().split(" ")[1]; 
			if (myA > myB){
				return 1;
			} else if (myA < myB){
				return -1;
			} else {
				return 0;
			}
		}
		function sortByNameDesc(a, b){
			var myA = $(a).data("questionnaire").name.toUpperCase().split(" ")[1];
			var myB = $(b).data("questionnaire").name.toUpperCase().split(" ")[1]; 
			if (myB > myA){
				return 1;
			} else if (myB < myA){
				return -1;
			} else {
				return 0;
			}
		}
		function loadData(){
			$.post("../mysql/data.php", {
				table: "churchMembershipFormReplies",
				order: "date",
				direction: "DESC",
				limit: "",
				searchField: "complete",
				searchString: "1",
				key: "<?echo crypt("He1sR1sen");?>"
			}, function(res){
				rows = res.split("|row|");
				for (x in rows){
					rows[x] = rows[x].split("|cell|");
				}
				loadTable(rows);
			});
		}
		function loadTable(rows){
			for (x in rows){
				var myDate = new Date(Date.parse(rows[x][3]));
				myDate =  (myDate.getMonth()+1) +"/"+ (myDate.getDate()+1) + "/"+ myDate.getFullYear();
				var who = "Action taken by: "
				who += (rows[x][5]) ? rows[x][5] : "Nobody";
				var whenDate = (rows[x][6] != "0000-00-00") ? new Date(Date.parse(rows[x][6])) : "";
				if (whenDate) whenDate = (whenDate.getMonth()+1) +"/"+ (whenDate.getDate()+1) +"/"+ whenDate.getFullYear();
				var when = (rows[x][6] != "0000-00-00") ? "On: "+whenDate : "";
				var htmlString = "<div class='message ";
				htmlString += rows[x][4] + "'>";
				htmlString += "<table>";
				htmlString += "<tr>";
				htmlString += "<td>";
				htmlString += rows[x][1];
				htmlString += "</td>";
				htmlString += "<td>";
				htmlString += myDate;
				htmlString += "</td>";
				htmlString += "</tr>";
				htmlString += "</table>";
				htmlString += "</div>";
				$("#mailbox").append(htmlString);
				$("#mailbox").children(":last").data("questionnaire", {id: rows[x][0], name: rows[x][1], reply: rows[x][2], date: myDate, mysqlDate:rows[x][3], read: rows[x][4], who: who, when: when, notes: rows[x][7]});
			}
			$("div.message").click(function(e){
				if ($(e.target).is("div.message")){
					var tar = e.target;
				} else{
					var tar = $(e.target).parents(".message");
				}
				selectMessage(tar);
			});
			showOnly("new");
		}
		function showOnly(str){
			$(".filter").removeClass("selected");
			$("#"+str+".filter").addClass("selected");
			$(".message").addClass("dontShow");
			$("."+str).removeClass("dontShow");
			updateCountPreviews();
		}
		function updateCountPreviews(){
			var newCount = $(".filter#new").text().replace(/\((.+)\)/g, "(" + $(".message.new").length + ")");
			var progressCount = $(".filter#inprogress").text().replace(/\((.+)\)/g, "(" + $(".message.inprogress").length + ")");
			var archivedCount = $(".filter#archived").text().replace(/\((.+)\)/g, "(" + $(".message.archived").length + ")");
			$(".filter#new").text(newCount);
			$(".filter#inprogress").text(progressCount);
			$(".filter#archived").text(archivedCount);
		}
		function selectMessage(tar){
			$(".message").removeClass("selected");
			$(tar).addClass("selected");
			$("#SMHeader").html("<div class='actions'>");
			if ($(tar).hasClass("new")){
				$(".actions").append("<button onClick='takeAction()'>Take Action</button>");	
			} else if ($(tar).hasClass("inprogress")){
				$(".actions").append("<br><button onclick='markAs(\"archived\")'>Mark as \"Archived\"</button>");
			} else {
				$(".actions").append("<br><button onclick='markAs(\"inprogress\")'>Mark as \"In Progress\"</button>");
			}
			$(".actions").append("<br><button onClick='editNotes()'>Edit notes</button>");
			$("#SMHeader").append("</div>");
			$("#SMHeader").append("<h3>"+$(tar).data("questionnaire").name+"</h3>");
			$("#SMHeader").append("<p>"+$(tar).data("questionnaire").who+"<br>");
			$("#SMHeader").append($(tar).data("questionnaire").when+"</p>");
			$("#SMHeader").append("<br><p>Notes:</p><p class='notes'>" + $(tar).data("questionnaire").notes + "</p>");
			$("#SMContent").html($(tar).data("questionnaire").reply);
		}
		function markAs(opt){
			var tar = $(".message.selected");
			$(tar).data("questionnaire").read = opt;
			$.post("../mysql/updateRow.php", {
				id: $(tar).data("questionnaire").id,
				table: "churchMembershipFormReplies",
				col: "read",
				value: opt,
				key: "<?echo crypt("He1sR1sen");?>"
			}, function(res){
				if (res.length > 0){
					$(tar).removeClass();
					$(tar).addClass("message");
					$(tar).addClass(opt);
					showOnly(opt);
					selectMessage(tar);
				} else {
					alert("Error connecting to server.");
				}
			});
		}
		function takeAction(){
			var tar = $(".message.selected");
			var person = prompt("Who's taking action?", "");
			if (person){
				$.post("../mysql/updateRow.php", {
					id: $(tar).data("questionnaire").id,
					table: "churchMembershipFormReplies",
					col: "who",
					value: person,
					key: "<?echo crypt("He1sR1sen");?>"
				}, function(res){
					if (res.length > 0){
						$(tar).data("questionnaire").who = "Action taken by: "+person;
						selectMessage(tar);
					} else {
						alert("Error connecting to server.");
					}
				});
				var date = new Date();
				formattedDate = (date.getFullYear())+"-"+(date.getMonth()+1)+"-"+(date.getDate());
				$.post("../mysql/updateRow.php", {
					id: $(tar).data("questionnaire").id,
					table: "churchMembershipFormReplies",
					col: "when",
					value: formattedDate,
					key: "<?echo crypt("He1sR1sen");?>"
				}, function(res){
					if (res.length > 0){
						formattedDate = (date.getMonth()+1)+"/"+(date.getDate())+"/"+(date.getFullYear());
						$(tar).data("questionnaire").when = "On: "+formattedDate;
						selectMessage(tar);
						markAs("inprogress");
					} else {
						alert("Error connecting to server.");
					}
				});
			}
		}
		function editNotes(){
			$(".notes").html("<textarea onblur='endEditNotes(this)'>"+$(".notes").html().replace(/\<br\>/g, "\n")+"</textarea>");
		}
		function endEditNotes(obj){
			if ($(obj).val() != $(".message.selected").data("questionnaire").notes){
				$.post("../mysql/updateRow.php", {
					id: $(".message.selected").data("questionnaire").id,
					table: "churchMembershipFormReplies",
					col: "notes",
					value: $(obj).val().replace(/\n/g, "<br>"),
					key: "<?echo crypt("He1sR1sen");?>"
				}, function(res){
					if (res.length > 0){
						$(".message.selected").data("questionnaire").notes = $(obj).val().replace(/\n/g, "<br>");
						selectMessage($(".message.selected"));
					} else {
						alert("Error connecting to server.");
					}
				});
			} else {
				selectMessage($(".message.selected"));
			}
		}
		function searchForMessage(val){
			if (val.length > 0){
				$(".message").each(function(){
					var newReg = new RegExp(val, "gi");
					if ($(this).text().search(newReg) >= 0){
						$(this).removeClass("hidden");
					} else {
						$(this).addClass("hidden");
					}
				});
			} else {
				$(".message").removeClass("hidden");
			}
		}
	</script>
<?
begin_body();
page_title_no_content($title);
$value = crypt("5HCC31d3rs");
if ($_POST['pass'] == "5HCC31d3rs"){
	?>
	<script type="text/javascript">
		document.cookie = "churchMembershipAdmin=<?echo $value;?>";
		document.location = document.location;
	</script>
	<?
} else if (!empty($_POST['pass'])){
	?>
	<script type="text/javascript">
		document.location.search = "?loginError=Incorrect+Password";
	</script>
	<?
}
if ($_COOKIE['churchMembershipAdmin'] != crypt("5HCC31d3rs", $_COOKIE['churchMembershipAdmin'])){
	?>
	<div id='loginBox'>
	<form method="post">
	<h3>Password</h3><br>
	<input name='pass' type="password" id='loginPassword'><br><br>
	<button>Login</button><br>
	<p id="loginError"><?echo $_GET['loginError']?></p>
	</form>
	</div>
	<p id='noPass'>Do you need the password? <a href="mailto:webservant@southhillcalvary.org?subject=Password%20for%20directory">Contact the Webservant</a></p>
	<?
	end_page_title();
	end_body();
	die();
}

?>
			<div id="picker">
				<input type="text" placeholder="Type here to search" id="searchBox" onkeyup="searchForMessage($(this).val())" />
				<div id="buttonHolder" >
					<div class="filter" id='new' onclick="showOnly('new')">New (0)</div>
					<div class="filter" id='inprogress' onclick="showOnly('inprogress')">In Progress (0)</div>
					<div class="filter" id='archived' onclick="showOnly('archived')">Archived (0)</div>
				</div>
				<div id="mailbox"></div>
				<div id='order'>
					Order by: 
					<select id='order' onchange="reorderTable(this.selectedIndex)">
						<option selected="selected">Date Descending</option>
						<option >Date Ascending</option>
						<option >Last Name Descending</option>
						<option >Last Name Ascending</option>
					</select>
				</div>
			</div>
			<div id='selectedMessage'>
				<div id='SMHeader'>No questionnaire selected...</div>
				<hr>
				<div id="SMContent"></div>
			</div>
<?
end_page_title();
end_body();
?>